const DragResize = (function () {
  // 默认配置
  const defaultOptions = {
    resizeClass: "resize-handle", // 拖拽手柄类名
    containerClass: "drag-container", // 容器类名
    leftClass: "left-section", // 左侧/顶部区域类名
    rightClass: "right-section", // 右侧/底部区域类名
    minSize: 32, // 最小尺寸（px）
    maxSize: null, // 最大尺寸（px）可选
    direction: "horizontal", // 拖拽方向：horizontal/vertical
  };

  // 初始化拖拽功能
  function init(options = {}) {
    const config = { ...defaultOptions, ...options };
    const resizeHandles = document.getElementsByClassName(config.resizeClass);

    // 遍历所有拖拽手柄
    Array.from(resizeHandles).forEach((handle) => {
      // 绑定鼠标按下事件
      handle.addEventListener(
        "mousedown",
        startDrag.bind(null, config, handle)
      );
    });
  }

  // 开始拖拽
  function startDrag(config, handle, e) {
    e.preventDefault();

    // 获取相关元素
    const container = handle.closest(`.${config.containerClass}`);
    const leftSection = handle.previousElementSibling;
    const rightSection = handle.nextElementSibling;

    if (!container || !leftSection || !rightSection) return;

    // 初始位置和尺寸
    const initialPos =
      config.direction === "horizontal" ? e.clientX : e.clientY;
    const containerSize =
      config.direction === "horizontal"
        ? container.clientWidth
        : container.clientHeight;
    const leftSize =
      config.direction === "horizontal"
        ? leftSection.clientWidth
        : leftSection.clientHeight;

    // 鼠标移动处理
    function onMouseMove(moveEvent) {
      const currentPos =
        config.direction === "horizontal"
          ? moveEvent.clientX
          : moveEvent.clientY;
      const delta = currentPos - initialPos;
      let newSize = leftSize + delta;

      // 限制尺寸范围
      newSize = Math.max(newSize, config.minSize);
      if (config.maxSize) newSize = Math.min(newSize, config.maxSize);

      // 计算右侧/底部区域尺寸
      const rightSize = containerSize - newSize - 10; // 10px间隙

      // 应用尺寸
      if (config.direction === "horizontal") {
        leftSection.style.width = `${newSize}px`;
        rightSection.style.width = `${rightSize}px`;
      } else {
        leftSection.style.height = `${newSize}px`;
        rightSection.style.height = `${rightSize}px`;
      }

      // 更新手柄位置（水平方向）
      if (config.direction === "horizontal") {
        handle.style.left = `${newSize}px`;
      }
    }

    // 鼠标松开处理
    function onMouseUp() {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
      handle.style.backgroundColor = "#f1f1f1"; // 恢复颜色
    }

    // 设置状态
    handle.style.backgroundColor = "#b9b9b9"; // 激活颜色
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);

    // 兼容IE的鼠标捕获（可选）
    try {
      handle.setCapture && handle.setCapture();
    } catch (err) {}
  }

  return {
    init,
    // 暴露配置常量方便外部使用
    defaultOptions,
  };
})();

export default DragResize;
